# -*- coding: utf-8 -*-

from pylons import config
from pylons.util import class_name_from_module_name

from autoadmin.lib.util import LoggerHandler

import sys

__all__ = ['ModelFinderError', 'ModelClassNotExist', 'ModelModuleNotExist',
           'ModelClassNotInCache', 'ModelFinder']

class ModelFinderError(Exception):
    pass

class ModelClassNotExist(ModelFinderError):
    pass

class ModelModuleNotExist(ModelFinderError):
    pass

class ModelClassNotInCache(ModelFinderError):
    pass

class ModelFinder(object):
    
    log = LoggerHandler()
    
    model_classes = None
    
    def __init__(self):
        if self.model_classes is None:
            self.model_classes = {}
    
    def in_cache(self):
        try:
            return self.model_classes[self.model_name]
        except KeyError:
            raise ModelClassNotInCache
    
    def get_model_package(self):
        try:
            return config['autoadmin.model.package']
        except KeyError:
            self.log.debug('`autoadmin.model.package` section undefined '+
                      'use default package: `%s`' % config['package'])
            
            return config['package']
    
    def load_module(self):
        try:
            __import__(self.full_module_name, {}, {}, str(self.model_name))
        except ImportError, e:
            raise ModelModuleNotExist, "Model module `%s` can't be found: %s" % \
                (self.full_module_name, e)
    
    def get_model_class(self):
        try:
            model = self.model_classes[self.model_name] = \
                getattr(sys.modules[self.full_module_name], self.model_class_name)
        except AttributeError:
            raise ModelClassNotExist, "Model class with name `%s` can't be found in %s" % \
                (self.model_class_name, self.full_module_name)
        
        return model
               
    def get_model(self, model_request_path):
        
        model_package = self.get_model_package()
        model_request_path = model_request_path.replace('/', '.')
        
        self.model_name = model_request_path.split('.')[-1]
        self.model_class_name = class_name_from_module_name(self.model_name)
        
        # модель в корне? 
        try:        
            model_path = '.' + model_request_path[:model_request_path.rindex('.')]
        except ValueError:
            model_path = ''

        self.full_module_name = model_package + model_path
        self.load_module()
        
        return self.get_model_class()

